var Goals = {
	init:function(){
		// test for complete goals
		$('.goal').each(function(){
			Goals.testGoalComplete($(this).find('[name=complete]:first'));
		});
	},
	validateSaveNewAction:function(form){
		var $form = $(form);
		if($form.find('[name=days]:checked').length == 0){
			var $label = $form.find('[name=days]:first').closest('.form-input').find('.form-input-label');
			var color = $label.css('color');
			$label.css({color:"red",fontWeight:"bold"});
			setTimeout(function(){	
				$label.css({color:color,fontWeight:"normal"});
			},1500);
			return false;
		} else {
			return true;
		}
	},
	cancelGoalAdd:function(){
		var $form = $('#new_goal');
		var $button = $('button#add_goal');
		$form.fadeOut();
		$button.fadeIn();
	},
	editMilestone:function(that){
		var $this = $(that);
		var $milestone = $this.closest('.milestone');
		var $goal = $this.closest('.goal');
		$milestone.addClass('edit');
		$milestone.find('input[type=checkbox]').hide();
		// limit the stuffs
		var locked = $milestone.find('input[name=locked]').val();
		var start = new Date ($goal.find('input[name=start]').val());
		var stop = new Date ($goal.find('input[name=stop]').val());
		if(locked == '0'){
			stop = DateTime.add(stop,-1);
			start = DateTime.add(start,1);
			// set the date
			start = DateTime.toString(start).substring(0,10);
			stop = DateTime.toString(stop).substring(0,10);
			var $date = $goal.find('input[name=date]');
			$date.datepicker('setEndDate',stop);
			$date.datepicker('setStartDate',start);
		} else {
			stop = DateTime.add(stop,-1);
			start = DateTime.add(start,1);
			start = DateTime.toString(start).substring(0,10);
			stop = DateTime.toString(stop).substring(0,10);
			var $date = $goal.find('input[name=date]');
			if(locked == -1){// is this the start goal? set end limit
				$date.datepicker('setEndDate',stop);
				$date.datepicker('setStartDate','01/01/1900');
			} else {// is this the end goal? set start limit
				$date.datepicker('setStartDate',start);
				$date.datepicker('setEndDate','12/31/2049');
			}
		}
	},
	cancelEditMilestone:function(that){
		var $this = $(that);
		var $milestone = $this.closest('.milestone');
		var milestoneID = $milestone.find("[name=milestoneID]").val();
		if(milestoneID != ""){
			$milestone.removeClass('edit');
			$milestone.find('input[type=checkbox]').show();
		} else { // if milestoneID == "" (new milestone) hide div and bring back button
			$milestone.parent().fadeOut();
			var $goal = $milestone.closest('.goal');
			$goal.find('.add_milestone_button').fadeIn();
			var $container = $goal.find('.add-button-container').fadeIn();
			$container.find('button').show();
		}	
	},
	toggleMilestoneComplete:function(that){
		var $this = $(that);
		var $milestone = $this.closest('.milestone');
		var milestoneID = $this.val();
		var $counterBlock = $('.counter-block[milestoneID='+milestoneID+']');
		if($this.is(':checked')){
			$milestone.addClass('complete');
			$counterBlock.addClass('complete');
		} else {
			$milestone.removeClass('complete');
			$counterBlock.removeClass('complete');
		}
		Goals.testGoalComplete($this);
	},
	testGoalComplete:function($checkbox){
		var $goal = $checkbox.closest('.goal');
		var $checkboxes = $goal.find('input[name=complete]');
		var $checked = $goal.find('input[name=complete]:checked');
		var $crosshairs = $goal.find('.fa-crosshairs,.fa-frown-o');
		var $trophy = $goal.find('.trophy-case');
		if($checkboxes.length == $checked.length){
			$goal.addClass('completed');
			$crosshairs.hide();
			$trophy.css({display:"inline-block"});
		} else {
			$goal.removeClass('completed');
			$crosshairs.show();
			$trophy.hide();
		}
	},
	showAddMilestone:function(that){
		var $this = $(that);
		var $goal = $this.closest('.widget-form');
		var $add = $goal.find('.add_milestone');
		var $addContainer = $goal.find('.add-button-container').hide();
		$this.fadeOut();
		$add.fadeIn(function(){
			$add.find('[name=description]').focus();
		});
		// fix date range according to goal start and end
		var start = new Date ($goal.find('input[name=start]').val());
		start = DateTime.add(start,1);
		start = DateTime.toString(start).substring(0,10);
		var stop = new Date ($goal.find('input[name=stop]').val());
		stop = DateTime.add(stop,-1);
		stop = DateTime.toString(stop).substring(0,10);
		var $date = $goal.find('input[name=date]');
		$date.datepicker('setStartDate',start);
		$date.datepicker('setEndDate',stop);
	},
	saveMilestoneComplete:function(that,milestoneID){
		var $this = $(that);
		var complete = $this.is(':checked');
		var $milestone = $this.closest('.milestone');
		$this.prop('disabled',true);
		Ajax.run({
			method:"goalService.saveMilestoneComplete",
			args:{milestoneID:milestoneID,complete:complete},
			onsuccess:function(){
				Goals.toggleMilestoneComplete(that);
				$this.prop('disabled',false);
			},
		});
		// see if it is the last milestone
		var $form = $milestone.closest('.goal_milestones');
		var $lastMilestone = $form.find('.milestone:last');
		var lastMilestoneID = $lastMilestone.find('[name=milestoneID]').val();
		if(complete && lastMilestoneID == milestoneID){
			$form.find('.milestone').each(function(){
				var id = $(this).find('[name=milestoneID]').val();
				var $checkbox = $(this).find('input[name=complete]');
				if(id != lastMilestoneID && !$checkbox.is(':checked')){
					$checkbox.click();
				}
			});
		}
	},
	deleteMilestone:function(that){
		if(!confirm('Remove Milestone?')){
			return;
		}
		var $this = $(that);
		var $milestone = $this.closest('.milestone');
		var milestoneID = $milestone.find('[name=milestoneID]').val();
		var year = $milestone.find('[name=year]').val();

		Main.func('goalController','deleteMilestone','&milestoneID='+milestoneID+'&year='+year);
	},
	showGoalEdit:function(that){
		var $this = $(that);
		var $form = $this.closest('form');
		Goals.setDateLimits($form);
		var $goal = $this.closest('.goal');
		var $edit = $goal.find('[name=goal_edit]');
		var $save = $goal.find('[name=goal_save]');
		var $cancel = $goal.find('[name=goal_cancel]');
		var $delete = $goal.find('[name=goal_delete]');
		var $name = $goal.find('input[name=name]:first');
		var $nameShow = $name.next();
		var $description = $goal.find('[name=description]:first');
		var $descriptionShow = $description.next();
		$edit.hide();
		$delete.show();
		$save.show();
		$cancel.show();
		$nameShow.hide();
		$name.show();
		$name.focus();
		$description.show();
		$descriptionShow.hide();
		$goal.addClass('edit');
	},
	hideGoalEdit:function(that){
		var $this = $(that);
		var $goal = $this.closest('.goal');
		var $edit = $goal.find('[name=goal_edit]');
		var $save = $goal.find('[name=goal_save]');
		var $delete = $goal.find('[name=goal_delete]');
		var $cancel = $goal.find('[name=goal_cancel]');
		var $name = $goal.find('input[name=name]:first');
		var $nameShow = $name.next();
		var $description = $goal.find('[name=description]:first');
		var $descriptionShow = $description.next();
		$edit.show();
		$save.hide();
		$cancel.hide();
		$delete.hide();
		$nameShow.show();
		$name.hide();
		$description.hide();
		$descriptionShow.show();
		$goal.find('.validation_issue').each(function() {
			$(this).hide();
		});
		$goal.removeClass('edit');
	},
	loadYear:function(){
		URL.setValue('year',$('[name=year]').val());
		window.location.reload();
	},
	editAction:function(that){
		var $this = $(that);
		$this.closest('.action').addClass('edit');
	},
	cancelEditAction:function(that){
		var $this = $(that);
		var $action = $this.closest('.action');
		var actionID = $action.find("[name=actionID]").val();
		if(actionID != ""){
			$action.removeClass('edit');
		} else { // if actionID == "" (new action) hide div and bring back button
			$action.parent().fadeOut();
			var $goal = $action.closest('.goal');
			$goal.find('.add_action_button').fadeIn();
		}
	},
	showAddAction:function(that){
		var $this = $(that);
		var $goal = $this.closest('.widget-form');
		var $add = $goal.find('.add_action');
		var $container = $goal.find('.add-action-container');
		$add.find('.form-input-value input:hidden,.form-input-value select:hidden,.form-input-value .form-input-value-list:hidden').each(function(){
			$(this).show();
		});
		$add.find('span.form-input-input-value').each(function(){
			$(this).hide();
		});
		$this.fadeOut();
		$add.fadeIn(function(){
			$add.find('input[name=name]').focus();
		});
		$container.fadeOut();
	},
	cancelAddAction:function(that){
		var $this = $(that);
		var $goal = $this.closest('.widget-form');
		var $add = $goal.find('.add_action');
		var $container = $goal.find('.add-action-container');
		$add.fadeOut();
		$container.fadeIn();
		$goal.find('.add_action_button').fadeIn();
	},
	deleteAction:function(that){
		if(!confirm('Remove Action Items?\n(Also removes its Workweek Actions)')){
			return;
		}
		var $this = $(that);
		var $action = $this.closest('.action');
		var actionID = $action.find('[name=actionID]').val();
		var year = $action.find('[name=year]').val();

		Main.func('goalController','deleteAction','&actionID='+actionID+'&year='+year);
	},
	showAddGoal:function(that){
		var $this = $(that);
		var $goal = $('#new_goal');
		$goal.fadeIn();
		Goals.showGoalEdit($goal.find('button[name=goal_edit]').get(0));
		$this.fadeOut();
	},
	cancelAddGoal:function(that){
		var $this = $(that);
		var $goal = $this.closest('.widget-form');
		$goal.toggleClass('expanded');
		$goal.find('.add_goal_button').fadeIn();
	},
	toggleActions:function(that){
		var $this = $(that);
		var $goal = $this.closest('.goal');
		var $action = $goal.find('.goal_actions_div');
		if($this.hasClass('fa-toggle-down')){
			//expand
			$action.slideDown(500);
			$this.addClass('fa-spin');
			setTimeout(function(){
				$this.removeClass('fa-spin');
				$this.removeClass('fa-toggle-down');
				$this.addClass('fa-toggle-up');
			},500);
		} else {
			//collapse
			$action.slideUp(500);
			$this.addClass('fa-spin');
			setTimeout(function(){
				$this.removeClass('fa-spin');
				$this.removeClass('fa-toggle-up');
				$this.addClass('fa-toggle-down');
			},500);
		}
	},
	toggleMilestones:function(that){
		var $this = $(that);
		var $goal = $this.closest('.goal');
		var $milestones = $goal.find('.goal_milestones');
		if($this.hasClass('fa-toggle-down')){
			//expand
			$milestones.slideDown(500);
			$this.addClass('fa-spin');
			setTimeout(function(){
				$this.removeClass('fa-spin');
				$this.removeClass('fa-toggle-down');
				$this.addClass('fa-toggle-up');
			},500);
		} else {
			//collapse
			$milestones.slideUp(500);
			$this.addClass('fa-spin');
			setTimeout(function(){
				$this.removeClass('fa-spin');
				$this.removeClass('fa-toggle-up');
				$this.addClass('fa-toggle-down');
			},500);
		}
	},
	deleteGoal:function(goalID,year){
		if(!confirm('Remove this Goal?\n(Also remove its Milestones)\n(Also removes its Action Plans)\n(Also removes its Workweek Actions)')){
			return;
		}

		Main.func('goalController','deleteGoal','&goalID='+goalID+'&year='+year);
	},
	reloadPage:function(){
		var string = "";
		if($('input[value=past]').is(':checked')){
			string += 'past';
		}
		if($('input[value=present]').is(':checked')){
			string += '_present';
		}		
		if($('input[value=future]').is(':checked')){
			string += '_future';
		}
		var url = URL.setValue('time_frame',string);
		window.location = url;
	},
	validateSaveGoal:function(that){
		var result = false;
		var $form = $(that);
		var end = $form.find('[name=stop]').val() || "";
		var start = $form.find('[name=start]').val() || "";
		var $measurable = $form.find('[name=measurable]');
		if(end == ""){
			return true;
		}
		if(!Valid.date(start) || !Valid.date(end)){
			return false
		}
		// compare dates
		var start = new Date(start);
		var end = new Date(end);
		// check measurable
		if($measurable.is(':checked')){
			return Valid.check($form.find('.form-input[name=Target]'));
			return false;
		}
		
		return DateTime.diff(start,end) >= 0;
	},
	setDateLimits:function($form){
		var $start = $form.find('input[name=start]');
		var $stop = $form.find('input[name=stop]');
		var start = $start.val();
		var stop = $stop.val();
		start = new Date(start);
		stop = new Date(stop);
		start = DateTime.add(start,1);
		stop = DateTime.add(stop,-1);
		start = DateTime.toString(start).substring(0,10);
		stop = DateTime.toString(stop).substring(0,10);
		if(Valid.date(start)){
			$stop.datepicker('setStartDate',start);
		} else {
			$stop.datepicker('setStartDate','01/01/1900');
		}
		if(Valid.date(stop)){
			$start.datepicker('setEndDate',stop);
		} else {
			$start.datepicker('setEndDate','12/31/2049');
		}
	},
	toggleMeasurable:function(that){
		var $this = $(that);
		var $form = $this.closest('form');
		var $unit = $form.find('input[name=unit]');
		var $unitField = $unit.closest('.form-input');
		var $target = $form.find('input[name=target]');
		if ($this.is(':checked')) {
			$unitField.show();
			// add validation for unit and target
			Validate.addValidation($unit,'required');
			Validate.addValidation($target,'required');
		}
		else {
			$unitField.hide();
			// remove validation for unit and target
			Validate.removeValidation($unit,'required');
			Validate.removeValidation($target,'required');
		}
	}
};
$(document).ready(function(){
	Goals.init();
	$(document).bind('dateChanged',function(e,that){
		var $this = $(that);
		var $form = $this.closest('form');
		var name = $this.attr('name');
		if(name == 'start' || name == 'stop'){
			Goals.setDateLimits($form);
		}
	});
	// bind change event to start and stop
	$('input[name=start],input[name=stop]').bind('change',function(){
		var $form = $(this).closest('form');
		Goals.setDateLimits($form);
	});
	// call toggle measurable on all checkboxes
	$('input[name=measurable]').each(function(){
		Goals.toggleMeasurable(this);
	});
});